package com.zl.tesseract.scanner.retrofit;


import android.support.annotation.NonNull;

import com.zl.tesseract.scanner.app.AppConfigs;
import com.zl.tesseract.scanner.retrofit.interceptor.AddCookiesInterceptor;
import com.zl.tesseract.scanner.retrofit.interceptor.ReceivedCookiesInterceptor;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * 网络请求工具类.
 *
 * @author: zhangyan
 * @date: 2018/8/7
 */
public class HttpUtil {

    private Retrofit retrofit;

    public static HttpUtil getInstance() {
        return Singleton.instance;
    }

    private static class Singleton {
        private static HttpUtil instance = new HttpUtil();
    }

    private HttpUtil() {
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        builder
                .addInterceptor(new AddCookiesInterceptor())
                .addInterceptor(new ReceivedCookiesInterceptor())
                .addInterceptor(new HttpLoggingInterceptor()
                        .setLevel(HttpLoggingInterceptor.Level.BODY));
        retrofit = new Retrofit.Builder()
                .baseUrl(AppConfigs.NET_BASE)
                .client(builder.build())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    private HttpService getHttpService() {
        return getService(HttpService.class);
    }

    private <T> T getService(Class<T> cls) {
        return retrofit.create(cls);
    }

    /**
     * 发送get请求
     *
     * @param url      地址
     * @param map      参数集合
     * @param callBack 回调
     */
    public void getRequestData(String url, LinkedHashMap<String, String> map, final NetCallBack callBack) {
        Map<String, String> headMap = new HashMap<>();
        getHttpService().getRequestData(headMap, url, map).enqueue(new Callback<String>() {
            @Override
            public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
                String result = response.body();
                if (callBack == null) {
                    return;
                }
                if (response.isSuccessful()) {
                    // 成功
                    String message = response.message();
                    if (response.code() == 200) {
                        callBack.onSuccess(result);
                    } else {
                        callBack.onFailure(response.code(), message, result);
                    }
                } else {
                    // 失败
                    try {
                        String errorBodyStr = response.errorBody().string();
                        JSONObject jsonObject = new JSONObject(errorBodyStr);
                        int code = jsonObject.optInt("code");
                        callBack.onFailure(code, "网络异常", null);
                    } catch (Exception e) {
                        e.printStackTrace();
                        callBack.onFailure(ErrorCodes.ERROR_DATA_PARSE, ErrorCodes.MSG_ERROR_DATA_PARSE, null);
                    }
                }
            }

            @Override
            public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
                if (callBack != null) {
                    callBack.onFailure(ErrorCodes.ERROR_NETWORK, "网络异常", null);
                }
            }
        });
    }

    /**
     * 发送put请求
     *
     * @param url：地址
     * @param map：参数
     * @param callBack：回调
     */
    public void putRequestData(String url, LinkedHashMap<String, String> map, final NetCallBack callBack) {
        Map<String, String> headMap = new HashMap<>();
        getHttpService().putRequestData(headMap, url, map).enqueue(new Callback<String>() {
            @Override
            public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
                if (callBack == null) {
                    return;
                }
                String result = response.body();
                if (response.isSuccessful()) {
                    // 成功
                    String message = response.message();
                    if (response.code() == 200) {
                        callBack.onSuccess(result);
                    } else {
                        callBack.onFailure(response.code(), message, result);
                    }
                } else {
                    // 失败
                    try {
                        String errorBodyStr = response.errorBody().string();
                        JSONObject jsonObject = new JSONObject(errorBodyStr);
                        int code = jsonObject.optInt("code");
                        callBack.onFailure(code, "网络异常", null);
                    } catch (Exception e) {
                        e.printStackTrace();
                        callBack.onFailure(ErrorCodes.ERROR_DATA_PARSE, ErrorCodes.MSG_ERROR_DATA_PARSE, null);
                    }
                }
            }

            @Override
            public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
                if (callBack != null) {
                    callBack.onFailure(ErrorCodes.ERROR_NETWORK, "网络异常", null);
                }
            }
        });
    }



}
